package de.dhe.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class FileHelper {

	public static void saveIMage(URL imageUrl, File out) {
		BufferedImage image = null;
		try {

			image = ImageIO.read(imageUrl);

			if (imageUrl.getFile().endsWith(".png")) {
				ImageIO.write(image, "png", out);
			} else if (imageUrl.getFile().endsWith(".jpg")) {
				ImageIO.write(image, "jpg", out);
			} else if (imageUrl.getFile().endsWith(".jpeg")) {
				ImageIO.write(image, "jpg", out);
			} else if (imageUrl.getFile().endsWith(".gif")) {
				ImageIO.write(image, "gif", out);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Done");
	}

	public static byte[] readBytes(File in) {
		FileInputStream fileInputStream = null;
		byte[] bFile = null;
		File file = new File("C:\\testing.txt");

		bFile = new byte[(int) file.length()];

		try {
			// convert file into array of bytes
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(bFile);
			fileInputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return bFile;
	}

	public static String getFileEnding(String name) {
		int indexOf = name.indexOf(".");
		name = name.substring(indexOf, name.length());
		return name;
	}

	public static void writeDebugPage(String string, int anbieter) {
		try {
			File debug = new File("target/" + anbieter + "_"
					+ System.currentTimeMillis() + ".txt");
			FileWriter writer = new FileWriter(debug);
			BufferedWriter buf = new BufferedWriter(writer);
			buf.write(string);
			buf.flush();
			buf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
